package com.party.admin.biz.merchantAnalyze;

import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.admin.biz.order.OrderBizService;
import com.party.admin.web.dto.output.merchantAnalyze.MerchantAnalyzeListOutput;
import com.party.admin.web.dto.output.merchantAnalyze.MerchantAnalyzeOutput;
import com.party.common.paging.Page;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.main.MainViewAnalyze;
import com.party.core.model.member.*;
import com.party.core.model.order.OrderForm;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.main.IMainViewAnalyzeService;
import com.party.core.service.member.*;
import com.party.core.service.order.IOrderFormService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.party.common.utils.DateUtils.addMonth;

/**
 * 合作商统计详情业务服务
 * Created by wei.li.
 *
 * @date 2017/12/12 0012
 * @time 16:25
 */

@Service
public class MemberMerchantDetailBizService {

    @Autowired
    private IMemberService memberService;

    @Autowired
    private IMemberActService memberActService;

    @Autowired
    private IMemberMerchantDetailService memberMerchantDetailService;

    @Autowired
    private IPartnerMemberService partnerMemberService;

    @Autowired
    private IOrderFormService orderFormService;

    @Autowired
    private IMerchantAnalyzeService merchantAnalyzeService;

    @Autowired
    private IMemberMerchantCountService memberMerchantCountService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private OrderBizService orderBizService;

    @Autowired
    private IMainViewAnalyzeService mainViewAnalyzeService;

    @Autowired
    private IMemberGroupService memberGroupService;


    //时间参数键
    private final static String DAY = "day";

    //总数参数键
    private final static String COUNT = "count";


    /**
     * 初始化
     */
    public void init(){
        List<MemberGroup> list = memberGroupService.getAllPartnerNoOpenStatus();
        for (MemberGroup m : list){
            //报名
            List<HashMap<String, Object>> count = memberActService.countByDate(null, null, m.getId());
            for (HashMap c : count){
                String date = (String) c.get(DAY);
                Integer num = Integer.valueOf(c.get(COUNT).toString());
                MemberMerchantDetail memberMerchantDetail
                        = memberMerchantDetailService.getSet(m.getId(), DateUtils.convertDate(date));
                memberMerchantDetail.setApplyNum(num);
                memberMerchantDetailService.update(memberMerchantDetail);
            }

            //会员
            List<HashMap<String, Object>> memberCount = partnerMemberService.countByDate(null, null, m.getId(), false);
            for (HashMap c : memberCount){
                String date = (String) c.get(DAY);
                Integer num = Integer.valueOf(c.get(COUNT).toString());
                MemberMerchantDetail memberMerchantDetail
                        = memberMerchantDetailService.getSet(m.getId(), DateUtils.convertDate(date));
                memberMerchantDetail.setMemberNum(num);
                memberMerchantDetailService.update(memberMerchantDetail);
            }

            List<HashMap<String, Object>> realNameCount = partnerMemberService.countByDate(null, null, m.getId(), true);
            for (HashMap rc : realNameCount){
                String date = (String) rc.get(DAY);
                Integer num = Integer.valueOf(rc.get(COUNT).toString());
                MemberMerchantDetail memberMerchantDetail
                        = memberMerchantDetailService.getSet(m.getId(), DateUtils.convertDate(date));
                memberMerchantDetail.setRealMemberNum(num);
                memberMerchantDetailService.update(memberMerchantDetail);
            }

            //订单
            List<HashMap<String, Object>> orderCount = orderFormService.countByDate(null, null, m.getId());
            for (HashMap c : orderCount){
                String date = (String) c.get(DAY);
                Integer num = Integer.valueOf(c.get(COUNT).toString());
                MemberMerchantDetail memberMerchantDetail
                        = memberMerchantDetailService.getSet(m.getId(), DateUtils.convertDate(date));
                memberMerchantDetail.setOrderNum(num);
                memberMerchantDetailService.update(memberMerchantDetail);
            }

            //金额
            List<HashMap<String, Double>> paymentCount = orderFormService.paymentSumByDate(null, null, m.getId());
            for (HashMap c : paymentCount){
                String date = (String) c.get(DAY);
                Double payment = (Double)c.get("sum");
                MemberMerchantDetail memberMerchantDetail
                        = memberMerchantDetailService.getSet(m.getId(), DateUtils.convertDate(date));
                memberMerchantDetail.setMoney(payment);
                memberMerchantDetailService.update(memberMerchantDetail);
            }

        }

        //更新浏览量
        MerchantAnalyzeQuery merchantAnalyzeQuery = new MerchantAnalyzeQuery();
        merchantAnalyzeQuery.setCreateEnd(DateUtils.todayDate());
        List<MerchantAnalyze> merchantAnalyzeList = merchantAnalyzeService.queryList(merchantAnalyzeQuery, null);
        for (MerchantAnalyze m : merchantAnalyzeList){
            MemberMerchantDetail memberMerchantDetail = memberMerchantDetailService.getSet(m.getMemberId(), m.getCreateDate());
            memberMerchantDetail.setViewNum(m.getViewNum());
            memberMerchantDetailService.update(memberMerchantDetail);
        }
    }


    /**
     * 转换为输出视图
     *
     * @param list 统计详情列表
     * @return 输出视图
     */
    public List<MerchantAnalyzeListOutput> transformDeatil(List<MemberMerchantDetailWithMember> list){
        List<MerchantAnalyzeListOutput> listOutputs
                = LangUtils.transform(list, new Function<MemberMerchantDetailWithMember, MerchantAnalyzeListOutput>() {
            @Override
            public MerchantAnalyzeListOutput apply(MemberMerchantDetailWithMember memberMerchantDetailWithMember) {
                return MerchantAnalyzeListOutput.transform(memberMerchantDetailWithMember);
            }
        });
        return listOutputs;
    }

    /**
     * 转化为输出视图
     *
     * @param list 统计列表
     * @return 输出视图
     */
    public List<MerchantAnalyzeListOutput> transformCount(List<MemberMerchantCountWithMember> list){
        List<MerchantAnalyzeListOutput> listOutputs
                = LangUtils.transform(list, new Function<MemberMerchantCountWithMember, MerchantAnalyzeListOutput>() {
            @Override
            public MerchantAnalyzeListOutput apply(MemberMerchantCountWithMember memberMerchantCountWithMember) {
                return MerchantAnalyzeListOutput.transform(memberMerchantCountWithMember);
            }
        });
        return listOutputs;
    }

    /**
     * 统计列表
     *
     * @param memberMerchantDetailQuery 查询参数
     * @param page 分页参数
     * @return 统计列表
     */
    public List<MerchantAnalyzeListOutput> list(MemberMerchantDetailQuery memberMerchantDetailQuery, Page page){
        if (null != memberMerchantDetailQuery.getTimeType()
                && !memberMerchantDetailQuery.getTimeType().equals(0)
                && !memberMerchantDetailQuery.getTimeType().equals(5)){
            String now = DateUtils.todayDate();
            String endTime = DateUtils.todayDate();
            String startTime = null;
            if (memberMerchantDetailQuery.getTimeType().equals(1)){
                startTime = now;
            }
            else if (memberMerchantDetailQuery.getTimeType().equals(2)){
                startTime = DateUtils.formatDate(DateUtils.addDay(now, -1));
                endTime = startTime;
            }
            else if (memberMerchantDetailQuery.getTimeType().equals(3)){
                startTime = DateUtils.formatDate(DateUtils.getFirstDayOfWeek(0));
                endTime = DateUtils.formatDate(DateUtils.getLastDayOfWeek(0));
            }
            else if (memberMerchantDetailQuery.getTimeType().equals(4)){
                startTime = DateUtils.formatDate(DateUtils.getFirstDayOfMonth(0));
                endTime = DateUtils.formatDate(DateUtils.getLastDayOfMonth(0));
            }
            memberMerchantDetailQuery.setCreateStart(startTime);
            memberMerchantDetailQuery.setCreateEnd(endTime);
            List<MemberMerchantDetailWithMember> memberMerchantDetailWithMemberList
                    = memberMerchantDetailService.sumList(memberMerchantDetailQuery, null, page);
            return this.transformDeatil(memberMerchantDetailWithMemberList);
        }

        List<MemberMerchantCountWithMember> memberMerchantCountWithMemberList
                = memberMerchantCountService
                .queryList(MemberMerchantCountQuery.transform(memberMerchantDetailQuery), null, page);
        return this.transformCount(memberMerchantCountWithMemberList);
    }


    /**
     * 统计详情
     *
     * @param memberId 统计总计编号
     * @return 统计视图
     */
    public HashMap<String, MerchantAnalyzeOutput> detail(String memberId){
        HashMap<String, MerchantAnalyzeOutput> map = Maps.newHashMap();
        String now = DateUtils.todayDate();
        MemberMerchantDetailQuery memberMerchantDetailQuery = new MemberMerchantDetailQuery();
        memberMerchantDetailQuery.setMemberId(memberId);
        memberMerchantDetailQuery.setCreateStart(now);
        memberMerchantDetailQuery.setCreateEnd(now);
        boolean isQueryChild = memberGroupService.isQueryChild(memberId);
        memberMerchantDetailQuery.setIsQueryChild(isQueryChild ? 1 : 0);

        //今日
        MemberMerchantDetail today = memberMerchantDetailService.sum(memberMerchantDetailQuery);

        //昨日
        String day = DateUtils.formatDate(DateUtils.addDay(now, -1));
        memberMerchantDetailQuery.setCreateStart(day);
        memberMerchantDetailQuery.setCreateEnd(day);
        MemberMerchantDetail yesterday = memberMerchantDetailService.sum(memberMerchantDetailQuery);

        //前日
        day = DateUtils.formatDate(DateUtils.addDay(now, -2));
        memberMerchantDetailQuery.setCreateStart(day);
        memberMerchantDetailQuery.setCreateEnd(day);
        MemberMerchantDetail beforeYDay = memberMerchantDetailService.sum(memberMerchantDetailQuery);

        //本周
        memberMerchantDetailQuery.setCreateStart(DateUtils.formatDate(DateUtils.getFirstDayOfWeek(0)));
        memberMerchantDetailQuery.setCreateEnd(DateUtils.formatDate(DateUtils.getLastDayOfWeek(0)));
        MemberMerchantDetail week = memberMerchantDetailService.sum(memberMerchantDetailQuery);

        //本月
        memberMerchantDetailQuery.setCreateStart(DateUtils.formatDate(DateUtils.getFirstDayOfMonth(0)));
        memberMerchantDetailQuery.setCreateEnd(DateUtils.formatDate(DateUtils.getLastDayOfMonth(0)));
        MemberMerchantDetail month = memberMerchantDetailService.sum(memberMerchantDetailQuery);

        //历史
        MemberMerchantCount history = memberMerchantCountService.findByMemberIdSum(memberId, isQueryChild);

        map.put("today", MerchantAnalyzeOutput.transform(today));
        map.put("yesterday", MerchantAnalyzeOutput.transform(yesterday));
        map.put("beforeYDay", MerchantAnalyzeOutput.transform(beforeYDay));
        map.put("week", MerchantAnalyzeOutput.transform(week));
        map.put("month", MerchantAnalyzeOutput.transform(month));
        map.put("history", MerchantAnalyzeOutput.transform(history));
        return map;
    }


    /**
     * 所有详情
     *
     * @return 统计数据
     */
    public HashMap<String, MerchantAnalyzeOutput> allDetail(){
        HashMap<String, MerchantAnalyzeOutput> map = Maps.newHashMap();
        String now = DateUtils.todayDate();
        MemberMerchantDetailQuery memberMerchantDetailQuery = new MemberMerchantDetailQuery();
        memberMerchantDetailQuery.setCreateStart(now);
        memberMerchantDetailQuery.setCreateEnd(now);

        //今日
        MemberMerchantDetail today = memberMerchantDetailService.allSum(memberMerchantDetailQuery);

        //昨日
        String day = DateUtils.formatDate(DateUtils.addDay(now, -1));
        memberMerchantDetailQuery.setCreateStart(day);
        memberMerchantDetailQuery.setCreateEnd(day);
        MemberMerchantDetail yesterday = memberMerchantDetailService.allSum(memberMerchantDetailQuery);

        //前日
        day = DateUtils.formatDate(DateUtils.addDay(now, -2));
        memberMerchantDetailQuery.setCreateStart(day);
        memberMerchantDetailQuery.setCreateEnd(day);
        MemberMerchantDetail beforeYDay = memberMerchantDetailService.allSum(memberMerchantDetailQuery);

        //本周
        memberMerchantDetailQuery.setCreateStart(DateUtils.formatDate(DateUtils.getFirstDayOfWeek(0)));
        memberMerchantDetailQuery.setCreateEnd(DateUtils.formatDate(DateUtils.getLastDayOfWeek(0)));
        MemberMerchantDetail week = memberMerchantDetailService.allSum(memberMerchantDetailQuery);

        //本月
        memberMerchantDetailQuery.setCreateStart(DateUtils.formatDate(DateUtils.getFirstDayOfMonth(0)));
        memberMerchantDetailQuery.setCreateEnd(DateUtils.formatDate(DateUtils.getLastDayOfMonth(0)));
        MemberMerchantDetail month = memberMerchantDetailService.allSum(memberMerchantDetailQuery);

        //历史
        MemberMerchantCount history = memberMerchantCountService.sum();

        map.put("today", MerchantAnalyzeOutput.transform(today));
        map.put("yesterday", MerchantAnalyzeOutput.transform(yesterday));
        map.put("beforeYDay", MerchantAnalyzeOutput.transform(beforeYDay));
        map.put("week", MerchantAnalyzeOutput.transform(week));
        map.put("month", MerchantAnalyzeOutput.transform(month));
        map.put("history", MerchantAnalyzeOutput.transform(history));
        return map;
    }

    /**
     * 时间列表
     * @param length 长度
     * @return 时间
     */
    public List<Date> dateList(Integer length){
        length = null == length ? 7: length;
        Date now = new Date();
        Date startDate = null;
        if(length == 30){
            startDate = addMonth(DateUtils.getTodayDate(), -1);
        }else{
            startDate = DateUtils.addDay(now, -(length - 1));
        }
        List<Date> dateList =  DateUtils.getDateDifference(startDate, now);
        return dateList;
    }

    /**
     * 时间列表
     * @param length 长度
     * @return 时间
     */
    public List<String> dateStringList(Integer length){
        List<Date> list = dateList(length);
        List<String> dateList = Lists.newArrayList();
        for (Date date : list){
            dateList.add(DateUtils.formatDate(date));
        }
        return dateList;
    }

    /**
     * 数据列表
     * @param length 时间长度
     * @param memberId 会员编号
     * @return 统计列表
     */
    public List<MemberMerchantDetail> lengthList(Integer length, String memberId){
        String now = DateUtils.todayDate();
        String startDay = null;
        if(length == 30){
            startDay = DateUtils.formatDate(addMonth(DateUtils.getTodayDate(), -1));
        }else{
            startDay = DateUtils.formatDate(DateUtils.addDay(now, -(length - 1)));
        }

        MemberMerchantDetailQuery memberMerchantDetailQuery = new MemberMerchantDetailQuery();
        memberMerchantDetailQuery.setMemberId(memberId);
        memberMerchantDetailQuery.setCreateStart(startDay);
        memberMerchantDetailQuery.setCreateEnd(now);
        boolean isQueryChild = memberGroupService.isQueryChild(memberId);
        memberMerchantDetailQuery.setIsQueryChild(isQueryChild ? 1 : 0);
        return memberMerchantDetailService.queryList(memberMerchantDetailQuery);
    }


    /**
     * 所有数据列表
     * @param length 长度
     * @return 统计数据
     */
    public List<MemberMerchantDetail> allLengthList(Integer length){
        String now = DateUtils.todayDate();
        String startDay = null;
        if(length == 30){
            startDay = DateUtils.formatDate(addMonth(DateUtils.getTodayDate(), -1));
        }else{
            startDay = DateUtils.formatDate(DateUtils.addDay(now, -(length - 1)));
        }

        MemberMerchantDetailQuery memberMerchantDetailQuery = new MemberMerchantDetailQuery();
        memberMerchantDetailQuery.setCreateStart(startDay);
        memberMerchantDetailQuery.setCreateEnd(now);
        return memberMerchantDetailService.allQueryList(memberMerchantDetailQuery);
    }


    /**
     * 图表统计数据
     * @param type 类型
     * @param length 长度
     * @param list 列表
     * @return 统计数据
     */
    public List<String> chartList(Integer type, Integer length, List<MemberMerchantDetail> list){
        List<Date> dateList = this.dateList(length);
        List<String> resultList = Lists.newArrayList();
        for (Date date : dateList){
            Object num = 0;
            for (MemberMerchantDetail memberMerchantDetail : list){
                if (DateUtils.formatDate(date).equals(DateUtils.formatDate(memberMerchantDetail.getCreateDate()))){
                    if (type == 0){
                        num = memberMerchantDetail.getApplyNum();
                    }
                    else if (type == 1){
                        num = memberMerchantDetail.getOrderNum();
                    }
                    else if (type == 2){
                        num = memberMerchantDetail.getMoney();
                    }
                    else if (type == 3){
                        num = memberMerchantDetail.getViewNum();
                    }
                    else if (type == 4){
                        num = memberMerchantDetail.getMemberNum();
                    }
                    else {
                        num = memberMerchantDetail.getApplyNum();
                    }
                    break;
                }
            }
            resultList.add(num.toString());
        }
        return resultList;
    }

    /**
     * 单个图表数据
     * @param length 长度
     * @param memberId 会员编号
     * @param type 类型
     * @return 统计数据
     */
    public List<String> oneChartList(Integer length, String memberId, Integer type){
        if (0 == length || -1 == length){
            return this.chartListForUnit(length, type, memberId);
        }
        List<MemberMerchantDetail> list = this.lengthList(length, memberId);
        return this.chartList(type, length, list);
    }

    /**
     * 列表数据
     * @param length 长度
     * @param type 类型
     * @return 统计数据
     */
    public List<String> allChaetList(Integer length,Integer type){
        if (0 == length || -1 == length|| -2==length){
            return this.chartListForUnit(length, type);
        }
        List<MemberMerchantDetail> list = this.allLengthList(length);
        return this.chartList(type, length, list);
    }


    /**
     * 获取时间单元图表
     * @param length 长度
     * @param type 类型
     * @return 数据
     */
    public List<String> chartListForUnit(Integer length, Integer type){
        String startDay;
        String endDay;

        List<String> list = Lists.newArrayList();
        int runNum = length == -2 ? 23:11;

        for (int i= runNum; i>=0; i--){
            startDay = 0 == length? DateUtils.formatDate(DateUtils.getFirstDayOfWeek(-i))
                    : DateUtils.formatDate(DateUtils.getFirstDayOfMonth(-i));

            endDay = 0== length? DateUtils.formatDate(DateUtils.getLastDayOfWeek(-i))
                    : DateUtils.formatDate(DateUtils.getLastDayOfMonth(-i));

            MemberMerchantDetailQuery query = new MemberMerchantDetailQuery();
            query.setCreateStart(startDay);
            query.setCreateEnd(endDay);
            MemberMerchantDetail memberMerchantDetail = memberMerchantDetailService.allSum(query);

            Object num;
            if (type == 0){
                num = memberMerchantDetail.getApplyNum();
            }
            else if (type == 1){
                num = memberMerchantDetail.getOrderNum();
            }
            else if (type == 2){
                num = memberMerchantDetail.getMoney();
            }
            else if (type == 3){
                num = memberMerchantDetail.getViewNum();
            }
            else if (type == 4){
                num = memberMerchantDetail.getMemberNum();
            }
            else {
                num = memberMerchantDetail.getApplyNum();
            }
            list.add(num.toString());
        }
        return list;
    }


    /**
     * 获取时间单元图表
     * @param length 长度
     * @param type 类型
     * @return 数据
     */
    public List<String> chartListForUnit(Integer length, Integer type, String memberId){
        String startDay;
        String endDay;

        List<String> list = Lists.newArrayList();
        for (int i= 11; i>=0; i--){
            startDay = 0 == length? DateUtils.formatDate(DateUtils.getFirstDayOfWeek(-i))
                    : DateUtils.formatDate(DateUtils.getFirstDayOfMonth(-i));

            endDay = 0== length? DateUtils.formatDate(DateUtils.getLastDayOfWeek(-i))
                    : DateUtils.formatDate(DateUtils.getLastDayOfMonth(-i));

            MemberMerchantDetailQuery query = new MemberMerchantDetailQuery();
            query.setCreateStart(startDay);
            query.setCreateEnd(endDay);
            query.setMemberId(memberId);
            MemberMerchantDetail memberMerchantDetail = memberMerchantDetailService.sum(query);

            Object num;
            if (type == 0){
                num = memberMerchantDetail.getApplyNum();
            }
            else if (type == 1){
                num = memberMerchantDetail.getOrderNum();
            }
            else if (type == 2){
                num = memberMerchantDetail.getMoney();
            }
            else if (type == 3){
                num = memberMerchantDetail.getViewNum();
            }
            else if (type == 4){
                num = memberMerchantDetail.getMemberNum();
            }
            else {
                num = memberMerchantDetail.getApplyNum();
            }
            list.add(num.toString());
        }
        return list;
    }

    /**
     * 校正昨天数据
     */
    public void yesterday(){
        List<MemberGroup> list = memberGroupService.getAllPartnerNoOpenStatus();
        Date date = DateUtils.addDay(DateUtils.today(), -1);
        String dateStr = DateUtils.formatDate(date);
        for (MemberGroup member : list){
            String mId = member.getId();
            Integer applyNum = memberActService.count(mId, dateStr, dateStr, false);
            Integer orderNum = orderFormService.count(dateStr, dateStr, mId, false);
            Double payment = orderFormService.paymentSum(dateStr, dateStr, mId, false);
            Integer memberNum = partnerMemberService.count(mId, dateStr, dateStr, false);
            Integer realNameNum = partnerMemberService.count(mId, dateStr, dateStr, true);
            Integer successNum = projectService.countBySuccessDate(date, mId);

            MemberMerchantDetail memberMerchantDetail = memberMerchantDetailService.getSet(mId, date);

            memberMerchantDetail.setApplyNum(applyNum);
            memberMerchantDetail.setOrderNum(orderNum);
            memberMerchantDetail.setMoney(payment);
            memberMerchantDetail.setMemberNum(memberNum);
            memberMerchantDetail.setRealMemberNum(realNameNum);
            memberMerchantDetail.setSuccessNum(successNum);
            memberMerchantDetailService.update(memberMerchantDetail);
        }
    }

    /**
     * 校正今天数据
     */
    public void today(){
        List<MemberGroup> list = memberGroupService.getAllPartnerNoOpenStatus();
        Date date = DateUtils.today();
        String dateStr = DateUtils.formatDate(date);
        for (MemberGroup memberGroup : list){
            String mId = memberGroup.getId();
            Integer applyNum = memberActService.count(mId, dateStr, dateStr, false);
            Integer orderNum = orderFormService.count(dateStr, dateStr, mId, false);
            Double payment = orderFormService.paymentSum(dateStr, dateStr, mId, false);
            Integer memberNum = partnerMemberService.count(mId, dateStr, dateStr, false);
            Integer realNameNum = partnerMemberService.count(mId, dateStr, dateStr, true);
            Integer successNum = projectService.countBySuccessDate(date, mId);

            MemberMerchantDetail memberMerchantDetail = memberMerchantDetailService.getSet(mId, date);

            memberMerchantDetail = this.reviseView(mId, date, memberMerchantDetail);
            memberMerchantDetail.setApplyNum(applyNum);
            memberMerchantDetail.setOrderNum(orderNum);
            memberMerchantDetail.setMoney(payment);
            memberMerchantDetail.setMemberNum(memberNum);
            memberMerchantDetail.setRealMemberNum(realNameNum);
            memberMerchantDetail.setSuccessNum(successNum);
            memberMerchantDetailService.update(memberMerchantDetail);
        }
    }

    /**
     * 校正浏览量
     * @param mId 机构
     * @param date 时间
     * @param memberMerchantDetail 统计详情
     * @return 校正浏览量
     */
    public MemberMerchantDetail reviseView(String mId, Date date, MemberMerchantDetail memberMerchantDetail){
        MemberMerchantDetailQuery memberMerchantDetailQuery = new MemberMerchantDetailQuery();
        memberMerchantDetailQuery.setMemberId(mId);
        memberMerchantDetailQuery.setCreateEnd(DateUtils.formatDate(DateUtils.addDay(date, -1)));
        return memberMerchantDetail;
    }

    /**
     * 跟新订单和金额
     * @param memberId 会员编号
     * @param payment 金额
     */
    public void updateOrderNum(String memberId, Float payment){
        if (!Strings.isNullOrEmpty(memberId)){
            MemberMerchantCount memberMerchantCount = memberMerchantCountService.getSet(memberId);
            if (null != memberMerchantCount.getOrderNum()){
                memberMerchantCount.setOrderNum(memberMerchantCount.getOrderNum() + 1);
            } else {
                memberMerchantCount.setOrderNum(1);
            }
            if (null != memberMerchantCount.getMoney()) {
                double addCount = BigDecimalUtils.add(memberMerchantCount.getMoney(), payment);
                double rountCount = BigDecimalUtils.round(addCount, 2);
                memberMerchantCount.setMoney(rountCount);
            } else {
                memberMerchantCount.setMoney(Double.valueOf(payment));
            }
            memberMerchantCountService.update(memberMerchantCount);

            MemberMerchantDetail memberMerchantDetail = memberMerchantDetailService.getSet(memberId, DateUtils.today());
            if (null != memberMerchantDetail.getOrderNum()){
                memberMerchantDetail.setOrderNum(memberMerchantDetail.getOrderNum() + 1);
            } else {
                memberMerchantDetail.setOrderNum(1);
            }

            if (null != memberMerchantDetail.getMoney()) {
                double add = BigDecimalUtils.add(memberMerchantDetail.getMoney(), payment);
                double round = BigDecimalUtils.round(add, 2);
                memberMerchantDetail.setMoney(round);
            } else {
                memberMerchantDetail.setMoney(Double.valueOf(payment));
            }
            memberMerchantDetailService.update(memberMerchantDetail);
        }
    }

    /**
     * 跟新报名数
     * @param memberId 会员编号
     */
    public void updateApplyNum(String memberId){
        if (!Strings.isNullOrEmpty(memberId)){
            MemberMerchantCount memberMerchantCount = memberMerchantCountService.getSet(memberId);
            if (null != memberMerchantCount.getApplyNum()){
                memberMerchantCount.setApplyNum(memberMerchantCount.getApplyNum() + 1);
            }
            else {
                memberMerchantCount.setApplyNum(1);
            }
            memberMerchantCountService.update(memberMerchantCount);

            MemberMerchantDetail memberMerchantDetail = memberMerchantDetailService.getSet(memberId, DateUtils.today());
            if (null != memberMerchantDetail.getApplyNum()){
                memberMerchantDetail.setApplyNum(memberMerchantDetail.getApplyNum() + 1);
            }
            else {
                memberMerchantDetail.setApplyNum(1);
            }
            memberMerchantDetailService.update(memberMerchantDetail);

        }
    }

    /**
     * 校正数据统计详情
     *
     * @param oldMemberId 旧的机构id
     * @param newMemberId 新的机构id
     */
    public void reviseMerchantDetail(String oldMemberId, String newMemberId) {
        MemberMerchantDetail query = new MemberMerchantDetail();
        query.setMemberId(oldMemberId);
        List<MemberMerchantDetail> oldDetails = memberMerchantDetailService.list(query);
        if (oldDetails.size() > 0) {
            for (MemberMerchantDetail oldDetail : oldDetails) {
                MemberMerchantDetail newDetail = memberMerchantDetailService.get(newMemberId, oldDetail.getCreateDate());
                boolean flag = false;
                if (newDetail != null) {
                    if (null != oldDetail.getOrderNum()) {
                        Integer orderNum = newDetail.getOrderNum() + oldDetail.getOrderNum();
                        newDetail.setOrderNum(orderNum);
                        flag = true;
                    }

                    if (null != oldDetail.getMoney()) {
                        Double money = BigDecimalUtils.add(newDetail.getMoney(), oldDetail.getMoney());
                        newDetail.setMoney(money);
                        flag = true;
                    }

                    if (null != oldDetail.getViewNum()) {
                        Long viewNum = newDetail.getViewNum() + oldDetail.getViewNum();
                        newDetail.setViewNum(viewNum);
                        flag = true;
                    }

                    if (flag) {
                        memberMerchantDetailService.update(newDetail);
                    }
                }
                if (flag) {
                    oldDetail.setOrderNum(0);
                    oldDetail.setMoney(0d);
                    oldDetail.setViewNum(0L);
                    memberMerchantDetailService.update(oldDetail);
                }
            }
        }
    }

    /**
     * 初始化成功数
     */
    public void initSuccessNum() {
        int pageIndex = 1;
        List<MemberMerchantDetail> list;
        MemberMerchantDetail param = new MemberMerchantDetailQuery();

        Page page = new Page();
        page.setPage(pageIndex);
        page.setLimit(1000);

        while (true) {
            list = memberMerchantDetailService.listPage(param, page);
            if (CollectionUtils.isEmpty(list)) {
                break;
            }
            list.forEach(detail -> {
                Integer successNum = projectService.countBySuccessDate(detail.getCreateDate(), detail.getMemberId());
                if (null == successNum || 0 == successNum) {
                    return;
                }
                detail.setSuccessNum(successNum);
                memberMerchantDetailService.update(detail);
            });
            page.setPage(++pageIndex);
        }
    }

    public void updateMainViewAnalyze(){
        Map<String, Object> params = Maps.newHashMap();
        params.put("isCrowdfund", "0");
        params.put("payment", 0);
        //获取支付成功的资金
        Double orderTotal = orderBizService.getOrderTotal(new OrderForm(), params, false, true);
        //获取已经退款的资金
        Double refundOrderTotal = orderBizService.getOrderTotal(new OrderForm(), params, false, false);

        //(平台+机构)
        //所有资金数
        double allTotal = BigDecimalUtils.add(orderTotal, refundOrderTotal);
        //所有注册会员数
        Integer allMember = memberService.allValidCount();
        //所有订单数
        Integer allOrder = orderFormService.allValidCount();
        //所有报名数
        Integer allApply = memberActService.allCount();


        //更新所有统计数(平台+机构)
        MainViewAnalyze mvlD= mainViewAnalyzeService.getMainView(new MainViewAnalyze(0,"total","SYSTEM"));
        mvlD.setMoney(allTotal);
        mvlD.setMemberNum(allMember.longValue());
        mvlD.setApplyNum(allApply.longValue());
        mvlD.setOrderNum(allOrder.longValue());

        mainViewAnalyzeService.update(mvlD);






        //获取机构下的统计数据
        Map<String,MerchantAnalyzeOutput> map = allDetail();
        //遍历以时间为key的map
        Set<Map.Entry<String,MerchantAnalyzeOutput>> entrySet=map.entrySet();
        for(Map.Entry<String, MerchantAnalyzeOutput> entry:entrySet){
            String key=entry.getKey();
            MerchantAnalyzeOutput val=entry.getValue();

            //更新所有统计数(机构)
            MainViewAnalyze mvlVb= mainViewAnalyzeService.getMainView(new MainViewAnalyze(0,key,"SYSTEM"));
            mvlVb.setMoney(val.getMoney());
            mvlVb.setApplyNum(val.getApplyNum().longValue());
            mvlVb.setOrderNum(val.getOrderNum().longValue());
            mvlVb.setViewNum(val.getViewNum());
            mvlVb.setMemberNum(val.getMemberNum().longValue());
            mvlVb.setRealMemberNum(val.getRealMemberNum().longValue());
            mvlVb.setSuccessNum(val.getSuccessNum().longValue());

            mainViewAnalyzeService.update(mvlVb);
        }
    }
}
